package cn.jingyinghui.rules.order;


import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.io.Resource;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

public class OrdersUtil {
    private static KieSession kieSession;

    static {
        // 初始化KieServices
        KieServices kieServices = KieServices.Factory.get();

        // 构建KieModule
       /* KieFileSystem kfs = kieServices.newKieFileSystem();
        Resource resource = kieServices.getResources().newClassPathResource("rules/order-rules.drl");
        kfs.write(resource);
        KieBuilder kieBuilder = kieServices.newKieBuilder(kfs);
        kieBuilder.buildAll();
        Results results = kieBuilder.getResults();
        if (results.hasMessages(Message.Level.ERROR)) {
            System.err.println(results.getMessages());
            throw new IllegalStateException("规则构建失败");
        }*/
        KieContainer kieContainer = kieServices.getKieClasspathContainer();
        // 创建KieSession
         kieSession = kieContainer.newKieSession("defaultKSession");
    }

    private static String getRuleContent() {
        // 实际项目中可以从文件或数据库加载规则
        return "package rules;\n" +
                "import cn.jingyinghui.rules.customer.Customer;\n" +
                "\n" +
                "rule \"Allow alcohol purchase for adults\"\n" +
                "    when\n" +
                "        $customer : Customer( age >= 18, canBuyAlcohol == false )\n" +
                "    then\n" +
                "        System.out.println(\"规则触发：允许 \" + $customer.getName() + \" 购买酒精饮料\");\n" +
                "        $customer.setCanBuyAlcohol(true);\n" +
                "        update($customer);\n" +
                "end\n" +
                "\n" +
                "rule \"Deny alcohol purchase for minors\"\n" +
                "    when\n" +
                "        $customer : Customer( age < 18, canBuyAlcohol == false )\n" +
                "    then\n" +
                "        System.out.println(\"规则触发：拒绝 \" + $customer.getName() + \" 购买酒精饮料，年龄不足\");\n" +
                "end";
    }

    public static KieSession getKieSession() {
        return kieSession;
    }
}